import React, { useMemo } from "react";
import { Form, Select } from "antd";
import { genWidget } from "../core";
import ItemLayout, { WrapProps } from "./formLabel";

export const genSelectWidget = (c: WidgetCategory): SelectWidget => {
  const base = genWidget(c);
  return {
    ...base,
    label: "下拉选择",
    placeholder: "请选择",
    options: [
      {
        label: "选项1",
        value: "1",
      },
      {
        label: "选项2",
        value: "2",
      },
    ],
    allowClear: true,
  };
};

const SelectWidgetRender = (props: WrapProps<SelectWidget>) => {
  const {
    uuid,
    options,
    name,
    isRequired,
    placeholder,
    allowClear,
    selectMode,
    isview,
  } = props;

  const hodleList = useMemo(
    () => options?.filter((x) => x.label && x.value) || [],
    [options]
  );
  return (
    <ItemLayout {...props}>
      {!isview && (
        <Select
          id={uuid}
          placeholder={placeholder}
          style={{ width: "100%" }}
          open={false}
        ></Select>
      )}
      {isview && (
        <Form.Item
          name={name}
          required={isRequired}
          rules={[
            {
              required: isRequired,
              message: placeholder,
            },
          ]}
        >
          <Select
            mode={selectMode}
            id={uuid}
            placeholder={placeholder}
            allowClear={allowClear}
            style={{ width: "100%" }}
          >
            {hodleList.map((opt, i) => (
              <Select.Option value={opt.value} key={i}>
                {opt.label}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
      )}
    </ItemLayout>
  );
};

export default SelectWidgetRender;
